/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.squirrelm.my.controller;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.squirrelm.my.domain.Jipiao;
import org.squirrelm.my.service.JipiaoService;
import org.squirrelm.my.util.Common;

/**
 *
 * @author 松鼠M
 */
@Controller
public class JipiaoController {

    private final static LinkedHashMap<String[], LinkedHashMap<String, Integer>> dateData   = new LinkedHashMap<String[], LinkedHashMap<String, Integer>>(){{
        put(
            new String[]{"上海", "南宁"},
            new LinkedHashMap<String, Integer>(){{
                put("2012-09-29", 800);
                put("2012-09-30", 800);
                put("2012-10-01", 500);
            }}
        );
        put(
            new String[]{"南宁", "上海"},
            new LinkedHashMap<String, Integer>(){{
                put("2012-10-06", 500);
                put("2012-10-07", 800);
            }}
        );
    }};

    private final static String pageCharset = "UTF-8";

    @Autowired
    private JipiaoService   jipiaoService;

    @Autowired
    private TimeZone  tz;

    private final static String toMail          = "13601766737@139.com";
    private final static String toMailCharset   = "UTF-8";

    private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @RequestMapping(value = "/jipiao/task.html", method = RequestMethod.GET, produces = "text/html;charset=utf-8")
    public @ResponseBody String  page() throws IOException, ParseException {

        dateFormat.setTimeZone(tz);
        ArrayList<Integer> prices = new ArrayList<Integer>();
        StringBuilder out  = new StringBuilder();
        for(Map.Entry entry : dateData.entrySet()) {
            String city[]       = (String[]) entry.getKey();
            LinkedHashMap<String, Integer> dateMin = (LinkedHashMap<String, Integer>)entry.getValue();
            String fromCity     = city[0];
            String toCity       = city[1];
            String json         = null;
            for(Map.Entry ent : dateMin.entrySet()) {
                Date date   = dateFormat.parse((String) ent.getKey());
                int priceLimit  = (Integer)ent.getValue();
                if( json == null ) {
                    json = getPage(fromCity, toCity, date);
                }
                int price   = getPrice(json, fromCity, toCity, date);

                if( priceLimit != 0 && price <= priceLimit ) {
                    sendAlertEmail(date, fromCity, toCity, price, priceLimit);
                }

                prices.add(price);
                out.append((String) ent.getKey()).append(":").append(price).append("<br/>");
            }
        }

        Jipiao jipiao   = new Jipiao();
        jipiao.setFetchTime(Calendar.getInstance(tz).getTime());
        jipiao.setMinPrice(prices);
        jipiaoService.create(jipiao);

        return out.toString();
    }

    @RequestMapping(value = "/jipiao/list.html", method = RequestMethod.GET, produces = "text/html;charset=utf-8")
    public String list(Model model) {
        List<Jipiao> jipiaos    = jipiaoService.find(0, 20);
        model.addAttribute("jipiaos", jipiaos);
        return "jipiao/list";
    }

    private void sendAlertEmail(Date date, String fromCity, String toCity, int priceNow, int priceLimit) {
        StringBuilder buf   = new StringBuilder();
        buf.append(dateFormat.format(date))
                .append(fromCity).append("到").append(toCity).append("的机票价格")
                .append(priceNow).append("，低于").append(priceLimit).append("!");
        String subject  = null;
        try {
            subject  = new String(buf.toString().getBytes("ISO-8859-1"), toMailCharset);
        } catch (UnsupportedEncodingException e) {

        }
        String content  = subject;
        Common.sendMail(toMail, subject, content);
    }

    private int getPrice(String json, String fromCity, String toCity, Date date) throws IOException {
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp       = jsonFactory.createJsonParser(json);
        ObjectMapper m      = new ObjectMapper();
        JsonNode rootNode   = m.readValue(jp, JsonNode.class);
        JsonNode priceNode  = rootNode.path("out").path(dateFormat.format(date) + "|" + fromCity + "-" + toCity).path("pr");
	int price           = Integer.parseInt(priceNode.textValue());
        return price;
    }

    private String getPage(String fromCity, String toCity, Date firstDate) {
        String urlString      = getUrl(fromCity, toCity, firstDate);
	StringBuilder  buf = new StringBuilder();
	try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.152 Safari/535.19 CoolNovo/2.0.3.55");
            connection.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
            connection.setRequestProperty("UA-CPU", "x86");
            connection.setRequestProperty("Accept-Encoding", "gzip");//为什么没有deflate呢
            connection.setRequestProperty("Content-type", "text/html");
            connection.setRequestProperty("Cache-Control", "max-age=0");
            connection.setRequestProperty("Connection", "close"); //keep-Alive，有什么用呢，你不是在访问网站，你是在采集。嘿嘿。减轻别人的压力，也是减轻自己。
            connection.setUseCaches(false);//不要用cache，用了也没有什么用，因为我们不会经常对一个链接频繁访问。（针对程序）

            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == 200) {
                    InputStream stream = connection.getInputStream();
                    BufferedReader in = new BufferedReader(new InputStreamReader(stream, pageCharset));

                    String line;

                    while (null != (line = in.readLine())) {
                            buf.append(line).append("\n");
                    }

                    stream.close();
                    in.close();
                    connection.disconnect();
            }
	} catch (Exception e) {
            e.printStackTrace();
	}

	return buf.toString();
    }

    private String getUrl(String fromCity, String toCity, Date date) {
        String dateStr  = dateFormat.format(date);
        StringBuilder buf   = new StringBuilder();
        buf.append("http://ws.qunar.com/all_lp.jcp?");
        buf.append("from=").append(fromCity);
        buf.append("&to=").append(toCity);
        buf.append("&goDate=").append(dateStr).append("&backDate=").append(dateStr);
        String url  = buf.toString();
        return url;
    }
}